﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Lapas.Common.Controls
{
    public partial class TreeViewComboBox : ComboBox
    {
        protected override void OnPaint(PaintEventArgs pe)
        {
            base.OnPaint(pe);
        }

        ToolStripControlHost treeViewHost;
        ToolStripDropDown dropDown;
        public TreeViewComboBox()
        {
            TreeView treeView = new TreeView();
            treeView.BorderStyle = BorderStyle.None;
            treeView.Width = this.DropDownWidth;
            treeView.Height = this.DropDownHeight;
            treeViewHost = new ToolStripControlHost(treeView);

            // create drop down and add it

            dropDown = new ToolStripDropDown();
            dropDown.Height = this.DropDownHeight;
            dropDown.Width = this.DropDownWidth;
            dropDown.Items.Add(treeViewHost);

        }

        public TreeView TreeView
        {
            get { return treeViewHost.Control as TreeView; }
        }

        private void ShowDropDown()
        {
            if (dropDown != null)
            {
                treeViewHost.AutoSize = false;
                treeViewHost.Width = 205;
                treeViewHost.Height = 106;


                treeViewHost.Width = this.Width;
                treeViewHost.Height = DropDownHeight;

                dropDown.Show(this, 0, this.Height);
            }
        }

        private const int WM_USER = 0x0400,
                          WM_REFLECT = WM_USER + 0x1C00,
                          WM_COMMAND = 0x0111,
                          CBN_DROPDOWN = 7;

        public static int HIWORD(int n)
        {
            return (n >> 16) & 0xffff;
        }

        protected override void WndProc(ref Message m)
        {
            if (m.Msg == (WM_REFLECT + WM_COMMAND))
            {
                if (HIWORD((int)m.WParam) == CBN_DROPDOWN)
                {
                    ShowDropDown();
                    return;

                }
            }
            base.WndProc(ref m);
        }

        // Edit: 10:37, remember to dispose the dropdown as it's not in the control collection. 
        //protected override void Dispose(bool disposing)
        //{
        //    if (disposing)
        //    {
        //        if (dropDown != null)
        //        {
        //            dropDown.Dispose();
        //            dropDown = null;
        //        }
        //    }
        //    base.Dispose(disposing);
        //}
    }
}
